<template>
  <div>
    <div class="center">
      <el-form label-width="80px" ref="form" :rules="rules" :model="form">
        <h2>登录</h2>
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onLogin()">登录</el-button>
          <el-button @click="again">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        // 规则里面通常有三个属性
        // required 必填项 true false
        // trigger 触发条件
        // message 出错的提示语
        // 校验条件
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    onLogin() {
      this.$refs.form.validate((isValid) => {
        if (isValid) {
          this.$axios({
            method: "POST",
            url: "/login",
            data: this.form,
          }).then((res) => {
            console.log(res.data);
            // 登陆时需要存token
            localStorage.setItem("token", res.data.data.token);
            if (res.data.message == "登录成功") {
              this.$router.push("/");
              this.$message("登陆成功");
            }
          });
        }
      });
    },
    again() {
      this.$refs.form.validate((isValid) => {
        if (isValid) {
          this.form = { username: "", password: "" };
          this.$message("重置成功");
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #ccc;
}
.el-form {
  // text-align: center;
  width: 350px;
}
h2 {
  text-align: center;
  margin: 10px 0px 10px 25px;
}
</style>